package com.leo.sunnyweather.logic.network

import android.util.Log
import com.leo.sunnyweather.logic.model.PlaceResponse
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * Author: Leo Liao <lliao@midtronics.com>
 * Date: 31/01/2024 17:58
 * Description:
 */
object SunnyWeatherNetWork {
    private val placeService = ServiceCreator.create<PlaceService>()


    suspend fun getPlaceByName(name: String): PlaceResponse {
        return placeService.getPlaceByName(name).wait()
    }

    private suspend inline fun <reified T> Call<T>.wait(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                /**
                 * Invoked for a received HTTP response.
                 *
                 *
                 * Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
                 * Call [Response.isSuccessful] to determine if the response indicates success.
                 */
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) {
                        continuation.resume(body)
                    } else {
                        continuation.resumeWithException(RuntimeException("Response is empty!"))
                    }
                }

                /**
                 * Invoked when a network exception occurred talking to the server or when an unexpected
                 * exception occurred creating the request or processing the response.
                 */
                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }

            })
        }
    }
}